<template>
  <div class="merchant-reports">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商家违规举报管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchProcess"
              >批量处理</el-button
            >
            <el-button type="success" @click="exportReports"
              >导出数据</el-button
            >
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商家名称">
          <el-input
            v-model="searchForm.merchantName"
            placeholder="请输入商家名称"
          />
        </el-form-item>
        <el-form-item label="举报类型">
          <el-select
            v-model="searchForm.reportType"
            placeholder="请选择举报类型"
          >
            <el-option label="虚假宣传" value="false_advertising" />
            <el-option label="商品质量" value="product_quality" />
            <el-option label="服务态度" value="service_attitude" />
            <el-option label="价格欺诈" value="price_fraud" />
            <el-option label="卫生问题" value="hygiene" />
            <el-option label="其他" value="others" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="processed" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="举报时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="sortedReportsList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="reportId"
          label="举报ID"
          width="120"
          sortable="custom"
        />
        <el-table-column
          prop="merchantName"
          label="商家名称"
          min-width="180"
          sortable="custom"
        />
        <el-table-column prop="merchantType" label="商家类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{
              getMerchantTypeLabel(row.merchantType)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reportType"
          label="举报类型"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getReportTypeTag(row.reportType)">
              {{ getReportTypeLabel(row.reportType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reportContent"
          label="举报内容"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="reporterInfo"
          label="举报人"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="reportTime"
          label="举报时间"
          width="160"
          sortable="custom"
        />
        <el-table-column
          prop="status"
          label="处理状态"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                :disabled="row.status === 'processed'"
                @click="handleProcess(row)"
              >
                处理
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <!-- 空状态模板 -->
        <template #empty>
          <el-empty 
            description="暂无违规举报数据" 
            :image-size="200"
          >
            <el-button type="primary" @click="fetchReportsList">刷新数据</el-button>
          </el-empty>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="处理举报" width="500px">
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="processResult">
          <el-select
            v-model="processForm.processResult"
            placeholder="请选择处理方式"
          >
            <el-option label="警告" value="warning" />
            <el-option label="罚款" value="fine" />
            <el-option label="限制经营" value="restriction" />
            <el-option label="下架商品" value="remove_product" />
            <el-option label="永久封禁" value="permanent_ban" />
            <el-option label="驳回举报" value="reject" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="罚款金额"
          prop="fineAmount"
          v-if="processForm.processResult === 'fine'"
        >
          <el-input-number
            v-model="processForm.fineAmount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item
          label="限制天数"
          prop="restrictionDays"
          v-if="processForm.processResult === 'restriction'"
        >
          <el-input-number
            v-model="processForm.restrictionDays"
            :min="1"
            :max="365"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="处理说明" prop="description">
          <el-input
            v-model="processForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
          />
        </el-form-item>
        <el-form-item label="处理凭证">
          <el-upload
            action="/api/admin/upload"
            list-type="picture-card"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="通知商家">
          <el-switch v-model="processForm.notifyMerchant" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="举报详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="举报ID">{{
          currentDetail.reportId
        }}</el-descriptions-item>
        <el-descriptions-item label="商家名称">{{
          currentDetail.merchantName
        }}</el-descriptions-item>
        <el-descriptions-item label="商家类型">
          <el-tag size="small">{{
            getMerchantTypeLabel(currentDetail.merchantType)
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="举报类型">
          <el-tag :type="getReportTypeTag(currentDetail.reportType)">
            {{ getReportTypeLabel(currentDetail.reportType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="举报时间">{{
          currentDetail.reportTime
        }}</el-descriptions-item>
        <el-descriptions-item label="举报人">{{
          currentDetail.reporterInfo
        }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusTag(currentDetail.status)">
            {{ getStatusLabel(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="相关订单" v-if="currentDetail.orderId">
          {{ currentDetail.orderId }}
        </el-descriptions-item>
        <el-descriptions-item label="举报内容" :span="2">
          {{ currentDetail.reportContent }}
        </el-descriptions-item>
        <el-descriptions-item label="证据材料" :span="2">
          <el-image
            v-for="(url, index) in currentDetail.evidences"
            :key="index"
            :src="url"
            :preview-src-list="currentDetail.evidences"
            fit="cover"
            class="evidence-image"
          />
        </el-descriptions-item>
        <el-descriptions-item
          v-if="currentDetail.status === 'processed'"
          label="处理结果"
          :span="2"
        >
          <div>
            处理方式：{{ getProcessResultLabel(currentDetail.processResult) }}
          </div>
          <div>处理说明：{{ currentDetail.processDescription }}</div>
          <div>处理时间：{{ currentDetail.processTime }}</div>
          <div>处理人员：{{ currentDetail.processor }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

// 搜索表单
const searchForm = reactive({
  merchantName: "",
  reportType: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const reportsList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedReports = ref([]);

// 处理对话框
const processDialogVisible = ref(false);
const processForm = reactive({
  processResult: "",
  fineAmount: 0,
  restrictionDays: 0,
  description: "",
  notifyMerchant: false,
  isBatch: false,
  batchIds: [],
});

// 详情对话框
const detailDialogVisible = ref(false);
const currentDetail = ref({});

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 获取商家类型标签
const getMerchantTypeLabel = (type) => {
  const types = {
    food: "餐饮美食",
    retail: "零售商店",
    service: "生活服务",
    entertainment: "文化娱乐",
    other: "其他",
  };
  return types[type] || type;
};

// 获取举报类型标签
const getReportTypeLabel = (type) => {
  const types = {
    false_advertising: "虚假宣传",
    product_quality: "商品质量",
    service_attitude: "服务态度",
    price_fraud: "价格欺诈",
    hygiene: "卫生问题",
    others: "其他",
  };
  return types[type] || type;
};

// 获取举报类型标签样式
const getReportTypeTag = (type) => {
  const types = {
    false_advertising: "danger",
    product_quality: "warning",
    service_attitude: "warning",
    price_fraud: "danger",
    hygiene: "warning",
    others: "info",
  };
  return types[type] || "";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待处理",
    processing: "处理中",
    processed: "已处理",
    rejected: "已驳回",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    pending: "warning",
    processing: "primary",
    processed: "success",
    rejected: "info",
  };
  return statuses[status] || "";
};

// 获取处理结果标签
const getProcessResultLabel = (result) => {
  const results = {
    warning: "警告",
    fine: "罚款",
    restriction: "限制经营",
    remove_product: "下架商品",
    permanent_ban: "永久封禁",
    reject: "驳回举报",
  };
  return results[result] || result;
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchReportsList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    merchantName: "",
    reportType: "",
    status: "",
    dateRange: [],
  });
  handleSearch();
};

// 获取举报列表
const fetchReportsList = async () => {
  loading.value = true;
  
  try {
    // 构建查询参数
    const params = {};
    if (searchForm.merchantName) params.merchantName = searchForm.merchantName;
    if (searchForm.reportType) params.reportType = searchForm.reportType;
    if (searchForm.status) params.status = searchForm.status;
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
    }
    params.page = currentPage.value;
    params.size = pageSize.value;
    params.sortProp = sortConfig.prop;
    params.sortOrder = sortConfig.order;
    
    const response = await service.get('/admin/merchants/reports', { params });
    
    if (response.code === 200) {
      reportsList.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      // 使用测试数据
      // 已在脚本中设置的mockData
      total.value = reportsList.value.length;
    }
  } catch (error) {
    console.error("获取举报列表失败：", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchReportsList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchReportsList();
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
  fetchReportsList();
};

// 导出举报数据
const exportReports = () => {
  try {
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    
    // 准备导出数据
    const exportData = reportsList.value.map(item => ({
      '举报ID': item.reportId,
      '商家名称': item.merchantName,
      '商家类型': getMerchantTypeLabel(item.merchantType),
      '举报类型': getReportTypeLabel(item.reportType),
      '举报内容': item.reportContent,
      '举报人': item.reporterInfo,
      '举报时间': item.reportTime,
      '处理状态': getStatusLabel(item.status),
      '相关订单': item.orderId || '-',
      '处理结果': item.processResult ? getProcessResultLabel(item.processResult) : '-',
      '处理说明': item.processDescription || '-',
      '处理时间': item.processTime || '-',
      '处理人员': item.processor || '-',
    }));
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    
    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 举报ID
      { wch: 20 }, // 商家名称
      { wch: 10 }, // 商家类型
      { wch: 15 }, // 举报类型
      { wch: 30 }, // 举报内容
      { wch: 15 }, // 举报人
      { wch: 20 }, // 举报时间
      { wch: 10 }, // 处理状态
      { wch: 15 }, // 相关订单
      { wch: 15 }, // 处理结果
      { wch: 30 }, // 处理说明
      { wch: 20 }, // 处理时间
      { wch: 15 }  // 处理人员
    ];
    ws['!cols'] = colWidths;
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "商家违规举报数据");
    
    // 导出Excel
    XLSX.writeFile(wb, `商家违规举报数据_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败");
  }
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedReports.value = val;
};

// 批量处理
const handleBatchProcess = () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning("请选择要处理的举报");
    return;
  }
  
  ElMessageBox.confirm(`确定要批量处理选中的${selectedReports.value.length}条举报记录吗？`, "批量处理确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    processDialogVisible.value = true;
    // 设置批量处理的表单
    processForm.isBatch = true;
    processForm.batchIds = selectedReports.value.map(item => item.reportId);
  }).catch(() => {
    // 取消操作
  });
};

// 处理单个举报
const handleProcess = (row) => {
  currentDetail.value = row;
  processForm.processResult = "";
  processForm.fineAmount = 0;
  processForm.restrictionDays = 0;
  processForm.description = "";
  processForm.notifyMerchant = true;
  processForm.isBatch = false;
  processDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = row;
  detailDialogVisible.value = true;
};

// 处理表单验证规则
const processRules = {
  processResult: [
    { required: true, message: "请选择处理方式", trigger: "change" },
  ],
  fineAmount: [{ required: true, message: "请输入罚款金额", trigger: "blur" }],
  restrictionDays: [
    { required: true, message: "请输入限制天数", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入处理说明", trigger: "blur" }],
};

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return;
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        
        const requestData = {
          processResult: processForm.processResult,
          description: processForm.description,
          notifyMerchant: processForm.notifyMerchant
        };
        
        // 根据处理方式添加额外参数
        if (processForm.processResult === 'fine') {
          requestData.fineAmount = processForm.fineAmount;
        } else if (processForm.processResult === 'restriction') {
          requestData.restrictionDays = processForm.restrictionDays;
        }
        
        let response;
        if (processForm.isBatch) {
          // 批量处理
          requestData.reportIds = processForm.batchIds;
          response = await service.post('/admin/merchants/reports/batch-process', requestData);
        } else {
          // 单个处理
          response = await service.post(`/admin/merchants/reports/${currentDetail.value.reportId}/process`, requestData);
        }
        
        if (response.code === 200) {
          ElMessage.success("处理成功");
          processDialogVisible.value = false;
          fetchReportsList();
        } else {
          ElMessage.error(response.message || "处理失败");
        }
      } catch (error) {
        console.error("处理失败：", error);
        ElMessage.error("处理失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 文件上传相关方法
const handlePreview = (file) => {
  // 图片预览逻辑
  window.open(file.url);
};

const handleRemove = (file, fileList) => {
  // 实现文件移除逻辑
  console.log("文件已移除", file);
};

// 获取排序后的数据
const sortedReportsList = computed(() => {
  const list = [...reportsList.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理特殊字段的排序
    if (sortConfig.prop === "reportType") {
      aValue = getReportTypeLabel(aValue);
      bValue = getReportTypeLabel(bValue);
    } else if (sortConfig.prop === "status") {
      aValue = getStatusLabel(aValue);
      bValue = getStatusLabel(bValue);
    } else if (sortConfig.prop === "reportTime") {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 页面加载时获取数据
onMounted(() => {
  fetchReportsList();
});
</script>

<style scoped>
.merchant-reports {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.evidence-image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
